﻿using DotNetty.Codecs;
using DotNetty.Transport.Bootstrapping;
using DotNetty.Transport.Channels;
using DotNetty.Transport.Libuv;
using System;
using System.Threading.Tasks;

namespace TestNettyServer
{
    class Program
    {
        static async Task Main(string[] args)
        {
            Console.WriteLine("Hello World!");
            IEventLoopGroup bossGroup;
            IEventLoopGroup workerGroup;

            var dispatcher = new DispatcherEventLoopGroup();
            bossGroup = dispatcher;
            workerGroup = new WorkerEventLoopGroup(dispatcher);

            ServerBootstrap bootstrap = new ServerBootstrap();
            bootstrap.Group(bossGroup, workerGroup);
            bootstrap.Channel<TcpServerChannel>();
            bootstrap
                    .Option(ChannelOption.SoBacklog, 100)
                    .ChildHandler(new ActionChannelInitializer<IChannel>(channel =>
                    {
                        IChannelPipeline pipeline = channel.Pipeline;
                        pipeline.AddLast("framing-encoder", new LengthFieldPrepender(4, true));
                        pipeline.AddLast("framing-decoder", new LengthFieldBasedFrameDecoder(int.MaxValue, 0, 4, -4, 4));

                        pipeline.AddLast("echo", new EchoServerHandler());
                    }));

            IChannel boundChannel = await bootstrap.BindAsync(52013);

            Console.ReadLine();

            await boundChannel.CloseAsync();
            await Task.WhenAll(
                    bossGroup.ShutdownGracefullyAsync(TimeSpan.FromMilliseconds(100), TimeSpan.FromSeconds(1)),
                    workerGroup.ShutdownGracefullyAsync(TimeSpan.FromMilliseconds(100), TimeSpan.FromSeconds(1))
            );
        }
    }
}
